<template>
  <div class="article-list-container">
    <div class="filter-container">
      <el-input
          v-model="searchQuery"
          placeholder="请输入文章标题"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter="handleSearch"
      />
      <el-select v-model="form.categoryId" placeholder="文章分类" clearable style="width: 150px" class="filter-item">
        <el-option v-for="category in categoryOptions" :key="category.id" :label="category.name" :value="category.id"/>
      </el-select>
      <el-select v-model="form.tagId" placeholder="文章标签" clearable style="width: 150px" class="filter-item">
        <el-option v-for="tag in tagOptions" :key="tag.id" :label="tag.name" :value="tag.id"/>
      </el-select>
      <el-button type="primary" class="filter-item" @click="handleSearch">搜索</el-button>
      <el-button type="success" class="filter-item" @click="handleCreate">新增文章</el-button>
    </div>

    <el-table
        v-loading="loading"
        :data="articleList"
        border
        style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80"/>
      <el-table-column prop="title" label="标题" min-width="200"/>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{row}">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">{{ row.status === 1 ? '已发布' : '草稿' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="views" label="浏览量" width="100"/>
      <el-table-column prop="wordCount" label="文章字数" width="100"/>
      <el-table-column prop="pictureUrl" label="首图">
        <template #default="{row}">
          <el-image :src="row.pictureUrl">
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <icon-picture/>
                </el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="作者ID" width="100"/>
      <el-table-column prop="categoryId" label="分类" width="120">
        <template #default="{row}">
          <span>{{ findBlogCategory(row.categoryId) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{row}">
          <span>{{ formatTime(new Date(row.createTime)) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #default="{row}">
          <span>{{ formatTime(new Date(row.updateTime)) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{row}">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import {onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {deleteBlogById, findAllBlog} from '@/api/blog'
import {findAllCategory} from "@/api/category"
import {findAllTag} from "@/api/tag"
import {ElMessage, ElMessageBox} from "element-plus"


export default {
  name: 'ArticleList',
  setup() {
    const loading = ref(false)
    const searchQuery = ref('')
    const categoryValue = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(100)
    const form = reactive({
      categoryId: '',
      tagId: '',
      title: '',
    })
    const categoryOptions = ref([])   // 分类列表
    const tagOptions = ref([])        // 标签列表
    const articleList = ref([])       // 文章列表

    const router = useRouter()

    const handleSearch = () => {
      loading.value = true
      findAllBlog(form).then(res => {
        loading.value = false
        articleList.value = res.data
      })
    }

    const handleCreate = () => {
      router.push({
        path: '/article/create'
      })
    }

    const handleEdit = (row) => {
      console.log(row)
      router.push({
        path: `/article/edit/${row.id}`,
        query: {
          blog: row
        },
      })
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm(
          `确定要删除博客 "${row.title}" 吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(async () => {
        try {
          await deleteBlogById(row.id)
          ElMessage.success('删除成功!')
          handleSearch()
        } catch (error) {
          console.error('删除博客失败:', error)
          ElMessage.error('删除博客失败!')
        }
      }).catch(() => {
        // 取消删除操作
      })
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      // 重新加载数据
      handleSearch()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      // 重新加载数据
      handleSearch()
    }

    // 格式化时间
    const formatTime = (date) => {
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hours = date.getHours();
      let minutes = date.getMinutes();
      let seconds = date.getSeconds();

      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      hours = hours < 10 ? "0" + hours : hours;
      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    // 获取博客分类标题
    const findBlogCategory = (categoryId) => {
      if (categoryOptions.value) {
        const category = categoryOptions.value.filter(category => category.id === categoryId)[0]
        if (category) {
          return category.name
        }
      }
    }

    onMounted(() => {
      // 获取全部的分类
      findAllCategory().then(res => {
        categoryOptions.value = res.data
      })
      // 获取全部的标签
      findAllTag().then(res => {
        tagOptions.value = res.data
      })
      // 获取全部的博客
      handleSearch()
    })

    return {
      loading,
      searchQuery,
      categoryValue,
      categoryOptions,
      tagOptions,
      articleList,
      currentPage,
      pageSize,
      total,
      form,
      handleSearch,
      handleCreate,
      handleEdit,
      handleDelete,
      handleSizeChange,
      handleCurrentChange,
      formatTime,
      findBlogCategory,
    }
  }
}
</script>

<style scoped>
.article-list-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
